<?php


namespace app\index\controller;


use think\Controller;
use think\Validate;

class MessageController extends BaseController
{

    public function test(){
        $header = $this->request->header();
        if (!isset($header['token'])||empty($header['token'])){
            return json(['code'=>'0','mes'=>'请先登录'])->send();
        }

        return json($header);
    }
    public function addym(){
        return view();
    }
    public function addMess(){
        //获取传值
        $data = $this->request->param();
        $header = $this->request->header();
        if (!isset($header['token'])||empty($header['token'])||$header['token']=='null'){
            return json(['code'=>'0','mes'=>'请先登录'])->send();
        }
        $validate = new Validate([
            'content' => 'require',

        ]);
        $validate -> message([
            'content.require' => '内容不能为空',

        ]);
        if( !$validate->check($data) ){
            $this->error = $validate->getError();
            return json(['mse'=>$this->error]);
        }
        $data['user_id'] = $header['token'];
        $uid = db('user')->field('username')->where('user_id',$data['user_id'])->find();
        $data['username']=$uid['username'];
        $data['create_time']=time();

        $res=db('content')->insert($data);
        if ($res){
            return json(['code'=>'1','mse'=>'发布成功']);
        }
        return json(['code'=>'0','mse'=>'发布失败']);
    }
    public function select(){
        $data = $this->request->param();
        if (empty($data['content'])){
            return $this->error('搜索内容不能为空');
        }
        $where[] = ['username','like','%'.$data['content'].'%'];
        $where2[] = ['content','like','%'.$data['content'].'%'];
        $res = db('content')
            ->whereOr($where)
            ->whereOr($where2)
            ->select();
        if ($res){
            return json($res);
        }
        return $this->error('无相似内容');
    }

}